<template>
  <div class="edit">
    <!-- van-nav-bar
    title:标题
    left-arrow:左边小箭头       -->

    <!-- 渲染数据：
     传统：
        1：导入api
        2:调用
        3：存储渲染
     使用vuex存储数据 -->

    <van-nav-bar
      title="编辑资料"
      left-arrow
      @click-left="$router.push('/layout/mine')"
    ></van-nav-bar>
    <van-uploader
      :before-read="beforeRead"
      style="width:100%;"
      :after-read="afterRead"
    >
      <div class="img">
        <img class="avatar" :src="userInfo.photo" alt="" />
      </div>
    </van-uploader>
    <!-- <h3>{{ user.obj.name }}</h3> -->
    <!-- van-cell  title:左边文本  value:右边文本  is-link右边小箭头 -->
    <van-cell-group>
      <van-cell
        title="名称"
        :value="userInfo.name"
        is-link
        @click="nameShow = true"
      ></van-cell>
      <van-cell
        @click="genderShow = true"
        title="性别"
        :value="userInfo.gender === 0 ? '女' : '男'"
        is-link
      ></van-cell>
      <van-cell
        title="生日"
        @click="birthdayShow = true"
        :value="userInfo.birthday"
        is-link
      ></van-cell>
    </van-cell-group>
    <!-- <h2>{{ num }}</h2>
    <van-button @click="testClick">调用actions</van-button> -->
    <!-- 修改姓名弹框  -->
    <!-- 1:显示当前的用户名
    2：定义修改api与导入
    3:点击确定时调用api
    4:调用成功
       提示
       关闭弹框
       刷新用户信息 -->
    <van-popup v-model="nameShow" style="width:80%;">
      <h3 class="title">修改名称</h3>
      <!-- v-model:    :value="userInfo.name"   @input="userInfo.name=$event" -->
      <!-- <van-field :value="userInfo.name" @input="name = $event"></van-field> -->
      <van-field v-model="name"></van-field>
      <div class="btn">
        <van-button @click="nameShow = false">取消</van-button>
        <van-button @click="nameSubmit">确定</van-button>
      </div>
    </van-popup>
    <!-- 性别 修改的布局 -->
    <van-popup v-model="genderShow" position="bottom">
      <van-nav-bar
        title="修改性别"
        left-text="取消"
        @click-left="genderShow = false"
      ></van-nav-bar>
      <van-cell title="男" is-link @click="genderSubmit(1)"></van-cell>
      <van-cell title="女" is-link @click="genderSubmit(0)"></van-cell>
    </van-popup>
    <!-- 生日修改 -->
    <van-popup
      v-model="birthdayShow"
      position="bottom"
      @click-overlay="cancelEvent"
    >
      <van-datetime-picker
        v-model="birthday"
        type="date"
        title="选择年月日"
        :min-date="minDate"
        :max-date="maxDate"
        @cancel="cancelEvent"
        @confirm="birthdaySubmit"
      />
    </van-popup>

    <div class="box" v-if="cropShow">
      <VueCropper
        ref="cropper"
        :img="cropImg"
        autoCrop
        autoCropWidth="200px"
        autoCropHeight="200px"
        fixedBox
      >
      </VueCropper>
      <div class="btn">
        <van-button type="info" @click="cropSubmit">裁切</van-button>
        <van-button @click="cropShow = false">取消</van-button>
      </div>
    </div>
  </div>
</template>
<script>
import { mapState } from 'vuex'
import { userProfilePatch, userPhotoPatch } from '@/api/user'
import moment from 'moment'
import { VueCropper } from 'vue-cropper'
export default {
  components: {
    VueCropper
  },
  data () {
    return {
      cropImg: '',
      cropShow: false,
      nameShow: false,
      genderShow: false,
      birthdayShow: false,
      birthday: new Date(this.$store.state.userInfo.birthday),
      minDate: new Date('1900', '01', '01'),
      maxDate: new Date('2023', '12', '20'),
      name: ''
    }
  },
  // 侦听器处理
  watch: {
    userInfo: {
      handler (newVal) {
        this.name = newVal.name
        this.birthday = new Date(newVal.birthday)
      },
      immediate: true
    }
  },
  computed: {
    ...mapState(['userInfo', 'num'])
  },
  created () {
    this.$store.dispatch('getUserInfo')
  },
  methods: {
    testClick () {
      this.$store.dispatch('test', Date.now())
    },
    inputEvent (event) {},
    async setUser (key, value) {
      if (value === '' || value === this.userInfo[key]) {
        this.$toast.fail('请修改后再提交')
        return Promise.reject(new Error('error'))
      }

      await userProfilePatch({
        [key]: value
      })

      // 刷新用户信息
      this.$store.commit('setUserInfo', {
        ...this.userInfo,
        [key]: value
      })
      // 提示
      this.$toast.success('修改成功')
    },

    // 姓名确定
    async nameSubmit () {
      await this.setUser('name', this.name)
      // 关闭弹框
      this.nameShow = false
    },
    // 性别 修改
    async genderSubmit (gender) {
      await this.setUser('gender', gender)
      this.genderShow = false
    },
    // 生日弹框取消点击
    cancelEvent () {
      this.birthdayShow = false
      this.birthday = new Date(this.userInfo.birthday)
    },
    // 生日确定
    async birthdaySubmit () {
      // moment  1:安装  2:导入  3:基本转换  moment(时间值).format('YYYY-MM-DD')
      await this.setUser('birthday', moment(this.birthday).format('YYYY-MM-DD'))
      // 关闭弹框
      this.birthdayShow = false
    },
    // 上传前回调
    beforeRead (file) {
      const limitType = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!limitType) {
        this.$toast.fail('请上传1Mb内的jpg与png图片')
      }
      const limitSize = file.size / 1024 / 1024 < 1
      if (!limitSize) {
        this.$toast.fail('请上传1Mb内的jpg与png图片')
      }
      return limitType && limitSize
    },
    // 读取后的回调
    afterRead (res) {
      // base64图片  file文件对象
      // 打开裁切弹框
      this.cropShow = true
      // 给裁切组件的img赋值对应的base64
      this.cropImg = res.content
    },
    // 裁切确定点击
    // 1:定义头像上传api2:导入  3:裁切完成后调用4:调用成功  a:提示 b:修改用户信息
    cropSubmit () {
      this.$refs.cropper.getCropBlob(async data => {
        // 文件对象是formdata上传
        const formdata = new FormData()
        formdata.append('photo', data)
        const res = await userPhotoPatch(formdata)
        // 关闭弹框
        this.cropShow = false
        // 头像修改成功提示
        this.$toast.success('头像修改成功')
        // 修改用户信息头像
        this.$store.commit('setUserInfo', {
          ...this.userInfo,
          photo: res.data.data.photo
        })
      })
    }
  }
}
</script>
<style lang="less" scoped>
.img {
  width: 100vw;
  text-align: center;
  .avatar {
    width: 160px;
    height: 160px;
    border-radius: 50%;
    object-fit: cover;
    background-color: #000;
    margin: 10px 0;
  }
}
.title {
  text-align: center;
  line-height: 2.5em;
  border-bottom: 1px solid #ccc;
  margin-top: 20px;
}
.btn {
  display: flex;
  .van-button {
    flex: 1;
  }
}
.box {
  position: fixed;
  top: 0;
  left: 0;
  height: 100vh;
  width: 100vw;
  background-color: rgba(0, 0, 0, 0.3);
  .btn {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100vw;
    display: flex;
    justify-content: space-between;
  }
}
</style>
